package dubbo.netty;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.concurrent.Callable;

/**
 * 描述:
 *
 * @author
 * @created 2022/1/12 19:36
 */
public class NettyClientHandler extends ChannelInboundHandlerAdapter implements Callable {

    private ChannelHandlerContext context;//上下文

    private String result;

    private String param;//客户端调用方法时传入的参数

    /*被代理对象调用，发送数据给服务器，发送完wait，等待被唤醒*/
    @Override
    public synchronized Object call() throws Exception {
        context.writeAndFlush(param);
        /*进行wait*/
        wait();//等地啊channelRead获取结果后唤醒
        return result;
    }

    /*收到数据后会调用*/
    @Override
    public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        result = msg.toString();
        notify();//唤醒等待的线程
    }

    /*与服务器连接创建成功后就会被调用*/
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        context = ctx;
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }

    public String getParam() {
        return param;
    }

    public void setParam(String param) {
        this.param = param;
    }
}
